<?php
/**
 * CreateTime: 2023/9/5 10:47
 */

namespace App\Func\HuaWei;

use App\Func\AppFunc;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Obs\ObsClient;
use Obs\ObsException;

require_once __DIR__.'/../../../obs-autoloader.php';


class ObsFunc
{
    public $obsClient;
    public $bucketName = 'zmsf-records';//桶名字
    public $expires = 3600;

    public function __construct()
    {
        $ak = config('obs.AK',AppFunc::getHuaWeiConfig()::OBS_ACCESS_KEY);//这里我放到配置文件里获取
        $sk = config('obs.SK',AppFunc::getHuaWeiConfig()::OBS_SECRET_ACCESS_KEY);//这里我放到配置文件里获取
        // AK SK 获取方法：https://support.huaweicloud.com/qs-obs/obs_qs_0005.html

        $endpoint = AppFunc::getHuaWeiConfig()::OBS_TONG_URL;
        //华为云桶的访问域名 从创建的桶里获取

        $this->obsClient = ObsClient::factory(array (
            'key' => $ak,
            'secret' => $sk,
            'endpoint' => "obs.cn-southwest-2.myhuaweicloud.com",
        ));
    }


    public function downloadFileByUrl($url){
        $resp = $this->obsClient->getObject([
            'Bucket' => $this->bucketName,
            'Key' => $url,
            "SaveAsFile" => "/www/wwwroot/mediation/storage/app/obsx/".$url
        ]);
        return [
            'url' => $resp['SaveAsFile']
        ];
    }


    public function uploadImgAndFile(Request $request){
        $file = $request->file('file');
        //上传文件最大大小,单位M
        $maxSize = 20;
        //支持的上传文件类型
        $allowed_extensions = ["png", "jpg", "gif","pdf"];
        //返回信息json
        $data = ['code' => 200, 'msg' => '上传文件失败', 'data' => ''];
        if ($file->isValid()) {
            //检测文件类型
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext), $allowed_extensions)) {
                $data['msg'] = "请上传" . implode(",", $allowed_extensions) . "格式的文件";
                return response()->json($data);
            }
            //检测文件大小
            if ($file->getClientSize() > $maxSize * 1024 * 1024) {
                $data['msg'] = "文件大小限制" . $maxSize . "M";
                return response()->json($data);
            }
        } else {
            $data['msg'] = $file->getErrorMessage();
            return response()->json($data);
        }
        $newFile = date('Ymd')."/" .time() .".".$file->getClientOriginalExtension();
        try {
            $resp = $this->obsClient->putObject([
                'Bucket' => $this->bucketName,//桶名
                'Key' => $newFile,// （文件路径1/文件路径2/文件名.文件后缀）
                'Body' => fopen($file,'r'),
                'ACL' => ObsClient::AclPublicRead,//设置对象访问权限为公共读
            ]);
            if($resp ['HttpStatusCode']==200){//$resp ['HttpStatusCode']状态码 200就是成功
                $data = [
                    'code' => 0,
                    'msg' => '上传文件成功',
                    'url' => $resp ['ObjectURL'],//华为云上的文件地址
                    "data" => [
                        "src" => $resp ['ObjectURL']//华为云上的文件地址
                    ]
                ];
            }else{
                $data['data'] = $resp ['HttpStatusCode'].':'.$resp['Reason'];
            }
            return response()->json($data);

        } catch ( ObsException $e ) {
            return response()->json($data);
        }
    }

    /**
     * 上传视频
     */
    public function uploadVideo(Request $request)
    {
        //支持的上传图片类型
        $allowed_extensions = ["mp4", "wmv", "wav"];
        //返回信息json
        $data = ['code' => 200, 'msg' => '视频上传失败', 'data' => ''];
        $file = $request->file('file');
        if ($file->isValid()) {
            //检测视频类型
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext), $allowed_extensions)) {
                $data['msg'] = "请上传" . implode(",", $allowed_extensions) . "格式的视频";
                return response()->json($data);
            }
        } else {
            $data['msg'] = $file->getErrorMessage();
            return response()->json($data);
        }
        $newFile = date('Ymd')."/".time().".".$file->getClientOriginalExtension();
        try {
            $resp = $this->obsClient->putObject([
                'Bucket' => $this->bucketName,//桶名
                'Key' => $newFile,// 文件在桶里的路径
                'Body' => fopen($file,'r'),
                'ACL' => ObsClient::AclPublicRead,//设置对象访问权限为公共读
            ]);

            if($resp ['HttpStatusCode']==200){ //$resp ['HttpStatusCode']状态码 200就是成功
                $data = [
                    'code' => 0,
                    'msg' => '上传成功',
                    'url' => $resp ['ObjectURL'],//华为云上的文件地址
                    "data" => [
                        "src" => $resp ['ObjectURL']//华为云上的文件地址
                    ]
                ];
            } else {
                $data['data'] = $file->getErrorMessage();
            }
        }catch ( ObsException $e ) {
            return response([
                'code' => 1,
                'message' => '上传视频错误 请重新上传']);
        }

        return response()->json($data);
    }

    /**
     * 内部绝对地址直接上传文件
     * @param Request $request
     */
    public function uploadVideoByPath($fileUrl)
    {
        $newFile = date('Ymd')."/".time().".wav";
        try {
            $resp = $this->obsClient->putObject([
                'Bucket' => $this->bucketName,//桶名
                'Key' => $newFile,// 文件在桶里的路径
                'SourceFile' => $fileUrl,
//                'ACL' => ObsClient::AclPublicRead,//设置对象访问权限为公共读
            ]);

            if($resp ['HttpStatusCode']==200){ //$resp ['HttpStatusCode']状态码 200就是成功
                return [
                    'flag' => true,
                    'url' => $resp ['ObjectURL']
                ];
            } else {
                echo date("Ymd h:i:s")."\nerror:upload fail".$resp['message'];
                return [
                    'flag' => false
                ];
            }
        }catch ( ObsException $e ) {
            echo ($e->getMessage());
            return [
                'flag' => false
            ];
        }
    }

}